package com.zjsru.oneDay202204;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Author: likew
 * @Date: 2022/4/17
 *
 * 最常见的单词
 *
 * 输入:
 * paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
 * banned = ["hit"]
 * 输出: "ball"
 * 解释:
 * "hit" 出现了3次，但它是一个禁用的单词。
 * "ball" 出现了2次 (同时没有其他单词出现2次)，所以它是段落里出现次数最多的，且不在禁用列表中的单词。
 * 注意，所有这些单词在段落里不区分大小写，标点符号需要忽略（即使是紧挨着单词也忽略， 比如 "ball,"），
 * "hit"不是最终的答案，虽然它出现次数更多，但它在禁用单词列表中。
 */
public class mostCommonWord {
    public String mostCommonWord(String paragraph, String[] banned) {
        Set<String> set = new HashSet<>();
        for (String s: banned) {
            set.add(s);
        }
        char[] c = paragraph.toCharArray();
        int len = c.length;
        String ans = null;
        Map<String,Integer> map = new HashMap<>();
        for (int i = 0; i < len;) {
            if(!Character.isLetter(c[i]) && ++i>0 ) continue;
            int j = i;
            while(j < len && Character.isLetter(c[j])) j++;
            String sub = paragraph.substring(i,j).toLowerCase();
            i = j+1;
            //检查是否是ban词
            if(set.contains(sub)) continue;
            //按照出现次数存入
            map.put(sub,map.getOrDefault(sub,0)+1);
            //按照出现次数进行比对
            if(ans == null || map.get(sub) > map.get(ans)) ans = sub;
        }
        return ans;
    }
    
    public static void main(String[] args) {
        mostCommonWord mostCommonWord = new mostCommonWord();
        String paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.";
        String[] banned = new String[]{"hit"};
        System.out.println(mostCommonWord.mostCommonWord(paragraph, banned));
    }
}
